package com.godme.endpoint;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.godme.sentinel.MailSenderSentinelResource;
import com.godme.service.mail.CodeSender;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.Date;

@RefreshScope
@DubboService(interfaceClass = CodeSender.class)
public class MailSendEndpoint implements CodeSender {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailProperties mailProperties;

    @Value("${spring.mail.company}")
    private String company;

    @Value("${spring.mail.subject}")
    private String subject;

    @Value("${spring.mail.template}")
    private String template;

    @SentinelResource(value = "sendCode", fallback = "sendCodeFallback", blockHandler = "sendCodeBlock", fallbackClass = MailSenderSentinelResource.class, blockHandlerClass = MailSenderSentinelResource.class)
    public boolean sendCode(String email, String code) {
        try{
            MimeMessage message = createMessage(email+"@qq.com", code);
            mailSender.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    private MimeMessage createMessage(String to, String code) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(mailProperties.getUsername(), company);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(String.format(template, code));
        helper.setSentDate(new Date());
        return message;
    }
}
